package cn.com.zs.android.util;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

/**
 * 播放音乐的工具类
 * @author 曾帅
 */
public class MusicPlayerUtils {

	private MediaPlayer mediaPlayer;
	/** 首歌曲 **/
	private final static int music_first = 0;
	/** 当前播放歌曲的索引 **/
	private int currentListItme = music_first;
	
	/**
	 * 单曲播放
	 * @param res	音乐文件路径
	 */
	public void playMusic(Context context, int res) {
		this.startMusic(context, res);
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				mp.release();
			}
		});
	}

	/**
	 * 批量播放 + 循环
	 * @param path	音乐文件路径集合
	 */
	public void playMusic(final Context context, final List<Integer> musicList) {
		this.startMusic(context, musicList.get(currentListItme));
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				mp.release();
				// 循环播放
				if(++currentListItme >= musicList.size()) {
					currentListItme = music_first;
				}
				playMusic(context, musicList);
			}
		});
	}
	
	public void startMusic(Context context, int res) {
		try {
			mediaPlayer = MediaPlayer.create(context, res);
			this.stopMusic();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 继续播放
	 */
	public void goonMusic() {
		if (mediaPlayer != null) {
			try {
				mediaPlayer.start();
			} catch (IllegalStateException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 暂停播放
	 */
	public void pauseMusic() {
		if (mediaPlayer != null) {
			try {
				mediaPlayer.pause();
			} catch (IllegalStateException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

	/**
	 * 停止播放
	 */
	public void stopMusic() {
		if (mediaPlayer != null) {
			try {
				mediaPlayer.stop();
			} catch (IllegalStateException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
	
}
